
var app = getApp();
var util = require('../../../utils/util.js');
var Bmob = require('../../../utils/bmob.js');
var articleData =  {
  title: '',
  text : '',
  imgs : [],
  section_id: '',
  category_id : '',
  phone: '',
  latitude: '',
  longitude: ''
};
var isSubmiting = false;

Page({
  data: {
    communityId: '',
    articleData : {
      title : '',
      text : '',
      imgs : [],
      section_id: '',
      category_id: '',
      phone: '',
      latitude: '',
      longitude: ''
    },
    address: '',
    theme_color : '',
    selectedClassify: '',
    require_audit: '',
    require_loc: true,
    require_phone: true,
    fromCommunityPage: false,
    showSlectWindow: false,
    showClassifyBox: false,
    showCategoryList: false,
    selectedSectionIndex: '',
    selectedSectionName: '',
    sectionList: [],
    selectedCategoryIndex: '',
    selectedCategoryName: '',
    categoryList: []
  },
  onLoad: function(options){
    let that = this,
      communityId = options.detail,
      fromCommunityPage = options.from == 'communityPage';

    app.getStorage({
      key: 'communityThemeColor-' + communityId,
      success: function (res) {
        that.setData({ theme_color: res.data });
      }
    })

    let article_id = options.articleId;

    if(article_id){
      this.getArticle(article_id);
    }else {
      that.getCategory(communityId);
    }

    this.setData({
      'communityId': communityId || '',
      'articleId' : article_id || '',
      'require_audit': options.reqAudit || '',
      'articleData.section_id': communityId || '',
      'fromCommunityPage': fromCommunityPage
    });

  },
  submitData : function(event) {
    let that = this,
      title = articleData.title,
      text = articleData.text,
      need_loc = that.data.require_loc,
      need_phone = that.data.require_phone,
      latitude = need_loc ? that.data.articleData.latitude : '',
      longitude = need_loc ? that.data.articleData.longitude : '',
      address = need_loc ? that.data.address : '',
      phone = need_phone ? articleData.phone : '',
      communityId = this.data.communityId || this.data.articleData.section_id,
      images = that.data.articleData.imgs,
      categoryId = this.data.selectedCategoryIndex;

    if( !title ){
      app.showModal({content : '请填写标题'});
      return ;
    }
    if( !text ){
      app.showModal({content : '请填写话题内容'});
      return ;
    }
    if ( !this.data.selectedCategoryName ) {
      app.showModal({content : '请选择分类'});
      return ;
    }

    let url = '/index.php?r=AppSNS/AddArticle';
    let article_id = that.data.articleId;

    if(article_id){
      url = '/index.php?r=AppSNS/UpdateArticle';
    }

    if (isSubmiting) {
      app.showModal({
        content: '正在提交中，请勿重复点击',
        complete: function () {
          !isSubmiting && app.turnBack();
        }
      });
      return;
    }
    isSubmiting = true;

    var Section = Bmob.Object.extend("Section");
    var section = new Section();
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;
    section.set("title", title);
    section.set("phone", phone);
    section.set("content_text", text);
    section.set("imgs", images);
    section.set("categoryActive", categoryId);
    section.set("longitude", longitude);
    section.set("latitude", latitude);
    section.set("user", isme);
    section.set("status", 1);
    section.set("like_count", 0);
    section.set("read_count", 0);
    section.set("address", address);
    //添加数据，第一个入口参数是null
    section.save(null, {
      success: function (result) {
        let content = that.data.require_audit == 1 ? '提交成功，待审核' : '提交成功';
        app.showModal({
          content: content,
          complete: function () {
            articleData.title = '';
            articleData.text = '';
            app.turnBack();
          }
        });
        isSubmiting = false;
      },
      error: function (result, error) {
        // 添加失败
        console.log('创建日记失败');
        console.log(error);
        isSubmiting = false;
      },
  
       
    
    });

    /*
    app.sendRequest({
      hideLoading: true,
      url: url,
      data: {
        article_id : article_id,
        section_id : communityId || this.data.sectionList[this.data.selectedSectionIndex].id, //版块id
        category_id : categoryId || this.data.categoryList[this.data.selectedCategoryIndex].id, //分类id 可不传
        title : title ,
        text : text ,
        imgs : that.data.articleData.imgs ,
        is_carousel : 0, //是否开启轮播 1为开启 0不开启
        top_flag :  0, //是否置顶 1为置顶 0不置顶
        hot_flag: 0, //是否精品 1是 0否
        phone: phone,
        latitude: latitude,
        longitude: longitude,
        address: address
      },
      method: 'post',
      success: function (res) {
        if (res.status == 0) {
          app.globalData.communityPageRefresh = true;
          app.globalData.communityUsercenterRefresh = true;
        }
      },
      complete: function (res) {
        if (res.status == 0) {
          let content = that.data.require_audit == 1 ? '提交成功，待审核' : '提交成功';
          app.showModal({
            content: content,
            complete: function () {
              articleData.title = '';
              articleData.text = '';
              app.turnBack();
            }
          });
        }
        isSubmiting = false;
      }
    });*/
  },
  bindTitleInput : function(event) {
    let val = event.detail.value;
    articleData.title = val;
  },
  bindTextInput : function(event) {
    let val = event.detail.value;
    articleData.text = val;
  },
  bindPhoneInput: function (event) {
    let val = event.detail.value;
    articleData.phone = val;
  },
  bindPhoneBlur: function (event) {
    let val = event.detail.value;
    this.setData({'articleData.phone': val});
  },
  uploadImg : function(){
    var that = this,
      imgs = that.data.articleData.imgs;

    app.chooseImage(function(imageUrls){
      imgs = imgs.concat(imageUrls);
      that.setData({
        'articleData.imgs' : imgs
      });
    } , 9);
  },
  deleteImg : function(event){
    var index = event.currentTarget.dataset.index,
      imgs = this.data.articleData.imgs;

    imgs.splice(index , 1);
    this.setData({
      'articleData.imgs' : imgs
    });
  },
  getSections: function (communityId, callback) {
   
    /*
    app.sendRequest({
      url: '/index.php?r=AppSNS/GetSectionByPage',
      data: param,
      method: 'post',
      success: function (res) {
        let newdata = {};
        let sec = res.data[0];
        newdata.require_loc = sec.require_location == 1;
        newdata.require_phone = sec.require_phone == 1;
        if (!that.data.theme_color) {
          newdata.theme_color = sec.theme_color;
        }
        if (communityId) {
          newdata['selectedSectionName'] = sec.name;
          newdata['require_audit'] = sec.require_audit;
          newdata['showCategoryList'] = true;
        }
        newdata['sectionList'] = res.data;
        that.setData(newdata);
        that.getCategory(communityId || res.data[0].id);
        typeof callback == 'function' && callback(res.data);
      }
    });*/
  },
  getCategory : function(sectionId, callback) {
   
    var that = this;
    var franchiseeId = that.data.franchiseeId;
    var categoryList = Bmob.Object.extend("categroyList");

    var categoryList = new Bmob.Query(categoryList);
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Franchisee();
    franchisee.id = "g3HTd44c";
    categoryList.ascending("categroy");
    categoryList.equalTo("franchisee", franchisee);
    categoryList.find({
      success: function (data) {
        var categoryList = that.data.categoryList;
        for (var i = 0; i < data.length; i++) {
          var category = { category: 0, name: '全部' }
          category.category = data[i].get("categroy");
          category.name = data[i].get("name");
          categoryList.push(category)
        }
        var data = {};
        data.categoryList = categoryList
        that.setData(data);
      }



    })

  },
  getArticle : function(article_id) {
    var that = this;
    var that = this;
    var SectionInfo = Bmob.Object.extend("Section");
    var sectionInfo = new Bmob.Query(SectionInfo);


    sectionInfo.get(communityId, {
      success: function (data) {
        //  if (res.status == 0) {

        let info = data[i].attributes,
          ctext = that.showEllipsis(idata.content_text);

        idata.title = unescape(idata.title.replace(/\\u/g, "%u"));
        idata.content_text = ctext.text;
        idata.isellipsis = ctext.isellipsis;
        idata.likeAnimateShow = true;
        idata.createdAt = data[i].createdAt;


       
          newdata = {};

        newdata['communityId'] = info.categoryActive;
        newdata['articleData.title'] = info.title;
        newdata['articleData.text'] = info.content_text;
        newdata['articleData.imgs'] = info.imgs || [];
        newdata['articleData.phone'] = info.phone;
       
        newdata['articleData.latitude'] = info.latitude;
        newdata['articleData.longitude'] = info.longitude;
        newdata['address'] = info.address;

        articleData.title = info.title;
        articleData.text = info.content_text;

        that.setData({
          'selectedCategoryIndex': info.categoryActive,
          'selectedCategoryName': that.data.categoryList[info.categoryActive].name,
          'showCategoryList': true
        });
        // }
        that.getCategory(communityId);

      },
      fail: function (res) {
       console.log(res);
      }


    })

/*
    app.sendRequest({
      url: '/index.php?r=AppSNS/GetArticleByPage',
      data: {
        article_id: article_id,
        only_own_record: 1
      },
      method: 'post',
      success: function (res) {
        if (res.status == 0) {
          let info = res.data[0],
            newdata = {};

          newdata['communityId'] = info.section_id;
          newdata['articleData.title'] = info.title;
          newdata['articleData.text'] = info.content.text;
          newdata['articleData.imgs'] = info.content.imgs || [];
          newdata['articleData.phone'] = info.phone;
          newdata['articleData.section_id'] = info.section_id;
          newdata['articleData.category_id'] = info.category_id;
          newdata['articleData.latitude'] = info.latitude;
          newdata['articleData.longitude'] = info.longitude;
          newdata['address'] = info.address;

          articleData.title = info.title;
          articleData.text = info.content_text;
          that.setData({
            'selectedCategoryIndex': cateIdx,
            'selectedCategoryName': cate.name,
            'showCategoryList': true
          });
          // that.getLocByLatAndLng(info.latitude, info.longitude, function (data) {
          //   that.setData({ address: data.address });
          // })

          that.getSections(info.section_id);
          that.getCategory(info.section_id, function (data) {
            data.some((cate, cateIdx) => {
              that.setData({
                'selectedCategoryIndex': cateIdx,
                'selectedCategoryName': cate.name,
                'showCategoryList': true
              });
            });
          });

          that.setData(newdata);
        }
      }
    });*/
  },
  getAddress: function () {
    let that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          'articleData.latitude': res.latitude,
          'articleData.longitude': res.longitude,
          'address': res.address
        });
        if (!res.address) {
          that.getLocByLatAndLng(res.latitude, res.longitude, function (data) {
            that.setData({ address: data.address });
          })
        }
      },
      fail: function () { },
      complete: function () { }
    })
  },
  addressInput: function (event) {
    if (event.detail.value) {
      this.setData({
        'articleData.latitude': '',
        'articleData.longitude': '',
        'address': ''
      });
    }
  },
  getLocByLatAndLng: function (lat, lng, cb) {
    app.sendRequest({
      url: '/index.php?r=Map/GetAreaInfoByLatAndLng',
      data: {
        latitude: lat,
        longitude: lng
      },
      method: 'post',
      success: function (data) {
        if (data.status == 0 && typeof cb == 'function') {
          cb(data.data);
        }
      }
    })
  },
  showClassifyBox: function () {
    let showFlag = this.data.showClassifyBox;
    this.setData({showClassifyBox: !showFlag});
    if (!this.data.articleData.category_id) {
      this.setData({
        'articleData.category_id': 0,
        selectedClassify: '全部（默认）'
      });
    }
  },
  showSlectWindowAct: function () {
    if (this.data.showSlectWindow && this.data.selectedCategoryName && !this.data.showCategoryList) {
      this.setData({
        'showCategoryList': true
      });
    }
    this.setData({
      'showSlectWindow': !this.data.showSlectWindow
    });
  },
  selectSectionAct: function (e) {
    let currentTarget = e.currentTarget,
      dataset = currentTarget.dataset,
      secIndex = dataset.index,
      currentSection = this.data.sectionList[secIndex];
    this.setData({
      'selectedSectionIndex': secIndex,
      'selectedSectionName': currentSection.name,
      'require_audit': currentSection.require_audit,
      'require_loc': currentSection.require_location == 1,
      'require_phone': currentSection.require_phone == 1,
      'selectedCategoryIndex': '',
      'selectedCategoryName': '',
      'showCategoryList': true
    });
    this.getCategory(currentSection.id);
  },
  selectCategoryAct: function (e) {
    let currentTarget = e.currentTarget,
      dataset = currentTarget.dataset,
      cateIndex = dataset.index,
      currentCategory = this.data.categoryList[cateIndex];
    this.setData({
      'selectedCategoryIndex': currentCategory.category,
      'selectedCategoryName': currentCategory.name,
      'showSlectWindow': false
    });
  },
  changeShowListAct: function () {
    if (this.data.fromCommunityPage) {
      return;
    }
    this.setData({
      'showCategoryList': !this.data.showCategoryList
    });
  },
  stopPropagation: function () {

  },
  bindTextFocus: function () {
    this.data.showSlectWindow && this.showSlectWindowAct();
  }
})
